package czk.concrent.threadstatus.practice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 线程打断的练习
 *
 * @Author:ChenZhangKun
 * @Date: 2021/2/17 21:18
 */
public class InterruptBeautifulPractice {
    public static void main(String[] args) throws InterruptedException {
        Monitor monitor = new Monitor();
        monitor.start();
        Thread.sleep(2 * 1000);
        monitor.stop();
    }
}

class Monitor {
    /**
     * 定义线程
     */
    private Thread monitor;

    /**
     * 执行业务线程
     */
    public void start() {
        monitor = new Thread(() -> {
            while (true) {
                // 拿到线程状态
                boolean interrupted = monitor.isInterrupted();
                if (interrupted) {
                    System.out.println("线程被打断了");
                    // 执行业务
                    try {
                        this.service();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                }
                System.out.println("线程没有被打断");
            }
        });
        monitor.start();
    }

    /**
     * 执行业务线程
     */
    private void service() throws IOException {
        // 爬取百度页面
        HttpURLConnection connection = (HttpURLConnection) new URL("http://www.baidu.com").openConnection();
        // 创建页面集合
        List<String> list = new ArrayList<>(10);
        // 拿到输入流
        InputStream inputStream = connection.getInputStream();
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            // 按行读取
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                list.add(line);
            }
        }
        System.out.println(list);
    }

    /**
     * 打断线程
     */
    public void stop() {
        monitor.interrupt();
    }
}
